<template>
  <view v-if="isLogined" class="container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="header-title" :class="{ active: currentPage === 0 }">皮试检测记录</text>
      <text class="header-title" :class="{ active: currentPage === 1 }">胸片智检记录</text>
    </view>

    <!-- swiper 翻页 -->
    <swiper
      :autoplay="false"
      class="swiper-container"
      :current="currentPage"
      @change="onSwiperChange"
    >
      <!-- 皮试检测记录页面 -->
      <swiper-item class="swiper-page">
        <!-- 每个检测记录 -->
        <view
          class="record"
          v-for="record in records.slice()"
          :key="record.id"
          @click="toDetail(record.id)"
        >
          <view class="record-header" @click="toDetail(record.id)">
            <text class="record-title">皮试检测</text>
            <text class="record-date">{{ formatDate(record.created_at) }}</text>
          </view>
          <div class="line"></div>
          <view class="record-body">
            <view class="record-conclusion">
              <text class="conclusion-title">结论</text>
              <text :class="getConclusionClass(record.result)">
                {{ record.result }}
              </text>
            </view>
            <view class="record-main">
              <view class="record-images">
                <image :src="record.image" class="record-image"></image>
                <image :src="record.res_image" class="record-image"></image>
              </view>
              <view class="record-delete" @click.stop="deleteRecord(record.id)">
                <image class="delete-icon" src="../../static/icons/delete.png" />
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
      <!-- 问卷调查记录页面 -->
      <swiper-item></swiper-item>
    </swiper>
  </view>

  <view v-else class="container">
    <view class="login-container">
      <text class="login-text">请先登录...</text>
      <button class="login-button mt-8" @click="toLogin">前往登录</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRecordStore } from '@/store/record'
import { useUserStore } from '@/store/user'

const recordStore = useRecordStore()
const records = computed(() => recordStore.records)

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const isLogined = computed(() => userStore.isLogined)

const currentPage = ref(0)

// 组件挂载时自动加载记录数据
onMounted(() => {
  init()
})

const init = async () => {
  console.log('userInfo', userInfo.value)
  if (isLogined.value) {
    await recordStore.getRecords(userInfo.value.id)
    console.log('records', records.value)
  }
}

// 结论的样式根据不同结果变化
const getConclusionClass = (result: string) => {
  switch (result) {
    case '阴性':
      return 'conclusion-negative'
    case '一般阳性':
      return 'conclusion-normal-positive'
    case '中度阳性':
      return 'conclusion-moderate-positive'
    case '强阳性':
      return 'conclusion-severe-positive'
    default:
      return ''
  }
}

const toDetail = (recordId: number) => {
  recordStore.getCurrentRecord(recordId)
  uni.navigateTo({
    url: '/pages/record/detail',
  })
}

const deleteRecord = async (recordId: number) => {
  uni.showModal({
    title: '提示',
    content: '确认删除记录？',
    success: async function (res) {
      if (res.confirm) {
        console.log('删除记录，id:', recordId)
        handleDelete(recordId) // 将异步逻辑移到单独的函数中处理
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}

const handleDelete = async (recordId: number) => {
  try {
    await recordStore.deleteRecord(recordId)
    await recordStore.getRecords(userInfo.value.id)
  } catch (error) {
    console.error('删除记录失败:', error)
    uni.showToast({ title: '操作失败，请重试', icon: 'none' })
  }
}

// Swiper 滑动处理函数
const onSwiperChange = (e: any) => {
  const index = e.detail.current
  currentPage.value = index
}

const toLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login',
  })
}

const formatDate = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  padding: 20px;
  background: linear-gradient(180deg, rgba(215, 229, 247, 1) 0%, rgba(217, 234, 251, 0) 100%);
}

.header {
  position: fixed;
  margin-top: 30px;
  margin-bottom: 20px;
  z-index: 999;
  background: linear-gradient(180deg, rgba(215, 229, 247, 1) 0%, rgba(217, 234, 251, 0) 100%);
  .header-title {
    font-size: 16px;
    color: #333;
    margin-right: 10px;
    &.active {
      color: #007aff;
      font-weight: bold;
      font-size: 22px;
    }
  }
}

.swiper-container {
  padding-top: 80px;
}

.swiper-page {
  overflow-y: auto;
}

.record {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;

  .line {
    width: 100%;
    height: 1px;
    background-color: #e6e6e6;
    margin-top: 15px;
  }

  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    .record-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .record-date {
      font-size: 14px;
      color: #999;
    }
  }

  .record-body {
    margin-top: 10px;
    display: flex;
    flex-direction: column;

    .record-conclusion {
      margin-bottom: 5px;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      .conclusion-title {
        color: #999;
      }
    }

    .record-main {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-bottom: 10px;
      .record-images {
        display: flex;
        gap: 10px;
        .record-image {
          width: 80px;
          height: 80px;
          border-radius: 8px;
          object-fit: cover;
        }
      }
      .record-delete {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 40px;
        height: 30px;
        background-color: #bf2424;
        border-radius: 8px;
        .delete-icon {
          width: 25px;
          height: 20px;
        }
      }
    }
  }
}

.conclusion-negative {
  color: #28a745; /* 绿色 */
  font-weight: bold;
}

.conclusion-normal-positive {
  color: #e6d86b; /* 黄色 */
  font-weight: bold;
}

.conclusion-moderate-positive {
  color: #fd7e14; /* 橙色 */
  font-weight: bold;
}

.conclusion-severe-positive {
  color: #dc3545; /* 红色 */
  font-weight: bold;
}

.login-container {
  margin: 200px auto;
  text-align: center;

  .login-text {
    font-size: 17px;
  }
  .login-button {
    width: 80%;
    background-color: #0075fe;
    border-radius: 12px;
    color: #eee;
    margin-top: 100px;
  }
}
</style>
